package com.test.springboot.springBootUtils.conf;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

import lombok.extern.slf4j.Slf4j;

/**
 * 使用注解添加过滤器
 * @author huyong
 *
 */
@WebFilter(urlPatterns = "/*", filterName = "AnnoactionFilter", description = "使用注解添加过滤器", initParams = { @WebInitParam(name = "name", value = "huyong"), @WebInitParam(name = "age", value = "25")

}, asyncSupported = true

)
@Slf4j
public class LogFilterAnnoaction implements Filter {
	/**
	 * init 方法在项目启动的时候加载一次
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// 获取过滤器参数
		String filterName = filterConfig.getFilterName();
		String name = filterConfig.getInitParameter("name");
		String age = filterConfig.getInitParameter("age");
		log.info("filterName:{},name:{},age:{}", filterName, name, age);
		// 获取所有参数名称
		Enumeration<String> names = filterConfig.getInitParameterNames();
		while (names.hasMoreElements()) {
			String nam = (String) names.nextElement();
			log.info("name:{}", nam);
		}
		Filter.super.init(filterConfig);
	}

	@Override
	public void destroy() {
		log.info("过滤器销毁");
		Filter.super.destroy();
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		long start = System.currentTimeMillis();
		chain.doFilter(request, response);
		log.info("LogFilter2 Execute cost=" + (System.currentTimeMillis() - start));
	}

}
